<script lang="ts" setup>
import type { TreeNodeData } from '@arco-design/web-vue/es/tree/interface'
import { IconDown } from '@arco-design/web-vue/es/icon'
import { getCdnGroupListApi } from '@/apis/modules/cdn'

const originTreeData = defineModel('data', {
  default: [],
  required: true,
})
const target = defineModel<string[]>('target', {
  default: [],
  required: true,
})
const searchKey = ref('')
const group_id = ref('')
const fieldNames = { key: 'id', title: 'name', children: 'children' }
const treeData = computed(() => {
  if (!searchKey.value && !group_id.value)
    return originTreeData.value
  return searchData(searchKey.value, group_id.value)
})
// function searchData(keyword: string, secondKeyword: string) {
//   const loop = (data) => {
//     const result = []
//     const filterData = data.filter((item) => {
//       return secondKeyword === item.id
//     })
//     if (secondKeyword) {
//       data = filterData
//     }
//     data.forEach((item) => {
//       if (item.name?.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
//         result.push({ ...item })
//       } else if (item.children) {
//         const filterData = loop(item.children)
//         if (filterData.length) {
//           result.push({
//             ...item,
//             children: filterData,
//           })
//         }
//       }
//     })
//     return result
//   }

//   return loop(originTreeData.value)
// }

function searchData(keyword: string, secondKeyword: string) {
  // 第一步：如果有secondKeyword，先按id过滤
  let dataToSearch = originTreeData.value
  if (secondKeyword) {
    dataToSearch = filterTreeById(originTreeData.value, secondKeyword)
  }

  // 第二步：按keyword搜索
  if (keyword) {
    return searchByKeyword(dataToSearch, keyword)
  }

  return dataToSearch
}

// 按ID过滤树
function filterTreeById(data, targetId) {
  const loop = (nodes) => {
    const result = []

    nodes.forEach((node) => {
      if (String(node.id) === targetId) {
        // 保留所有属性，包括 expanded
        result.push({
          ...node,
          // 确保展开状态，可以根据需要调整
          // expanded: node.expanded !== undefined ? node.expanded : true,
          expanded: true,
        })
      } else if (node.children) {
        const filteredChildren = loop(node.children)
        if (filteredChildren.length > 0) {
          result.push({
            ...node,
            children: filteredChildren,
            // 如果有匹配的子节点，自动展开父节点
            expanded: true,
          })
        }
      }
    })

    return result
  }

  return loop(data)
}

function searchByKeyword(data, keyword) {
  const loop = (nodes) => {
    const result = []
    const lowerKeyword = keyword.toLowerCase()

    nodes.forEach((node) => {
      const matchName = node.name?.toLowerCase().includes(lowerKeyword)

      if (matchName) {
        result.push({
          ...node,
          // 匹配的节点自动展开
          expanded: true,
        })
      } else if (node.children) {
        const filteredChildren = loop(node.children)
        if (filteredChildren.length > 0) {
          result.push({
            ...node,
            children: filteredChildren,
            // 有匹配子节点时展开父节点
            expanded: true,
          })
        }
      }
    })

    return result
  }

  return loop(data)
}
// const treeData = computed(() => {
//   if (!searchKey.value && !group_id.value)
//     return originTreeData.value

//   return searchData(searchKey.value, group_id.value)
// })

// function searchData(keyword: string, secondKeyword: string) {
//   const loop = (data) => {
//     const result = []
//     data.forEach((item) => {
//       // 组合查询条件：满足第一个条件 OR 满足第二个条件
//       const matchFirst = keyword && item.name?.toLowerCase().includes(keyword.toLowerCase())
//       const matchSecond = secondKeyword && item.description?.toLowerCase().includes(secondKeyword.toLowerCase())

//       // 根据需求选择逻辑：AND 或者 OR
//       const isMatch = (matchFirst || matchSecond) // OR 逻辑
//       // const isMatch = (matchFirst && matchSecond) // AND 逻辑

//       if (isMatch) {
//         result.push({ ...item })
//       } else if (item.children) {
//         const filterData = loop(item.children)
//         if (filterData.length) {
//           result.push({
//             ...item,
//             children: filterData,
//           })
//         }
//       }
//     })
//     return result
//   }
//   return loop(originTreeData.value)
// }

function onSelect(
  _selectedKeys: Array<string | number>,
  info: {
    selected?: boolean
    selectedNodes: TreeNodeData[]
    node?: TreeNodeData
    e?: Event
  },
) {
  if (!info?.node?.children?.length) {
    if (target.value.includes(info?.node?.id as string)) {
      target.value = target.value.filter(item => item !== info?.node?.id)
    } else {
      target.value = [...target.value, info?.node?.id as string]
    }
  } else {
    if (info?.selected) {
      target.value = [
        ...target.value,
        ...info.node.children.map(item => item.id),
      ]
    } else {
      target.value = target.value.filter((item) => {
        return !info?.node?.children?.some(child => child?.id === item)
      })
    }
  }
}
function getMatchIndex(title: string) {
  if (!searchKey.value)
    return -1
  return title.toLowerCase().indexOf(searchKey.value.toLowerCase())
}

const ClusterOptions = ref<LabelValue[]>([])
// 获取集群列表
async function getGroupList() {
  const res = await getCdnGroupListApi({ limit: 0 })
  const list = res.list ?? []

  ClusterOptions.value = list
    .map(item => ({ label: item.name!, value: item.id! }))
    .filter(Boolean)
}

onMounted(() => {
  getGroupList()
})
const typeOptions = [
  {
    label: '边缘组',
    value: 1,
  },
  {
    label: '上游组',
    value: 2,
  },
]
</script>

<template>
  <section>
    <section class="mb-4 flex items-center justify-between">
      <section class="flex items-center gap-x-1">
        <i-icons-exclamation class="text-#8f959e !h-[14px] !w-[14px]" />
        <span class="whitespace-nowrap text-xs/5 text-#8f959e">上游组节点，安全配置不生效。</span>
      </section>
      <div>
        <a-select
          v-model="group_id"
          class="mr-4 !w-160px"
          placeholder="全部分组"
          :options="[{ label: '全部节点分组', value: '' }, ...ClusterOptions]"
        />

        <a-input-search
          v-model="searchKey"
          allow-clear
          class="!w-232px"
          placeholder="默认按照节点名称搜索"
        />
      </div>
    </section>
    <section
      class="overflow-auto border border-[#F2F3F5] rounded-2 border-solid px-3 pt-4"
    >
      <a-tree
        v-if="originTreeData.length && treeData.length"
        v-model:checked-keys="target"
        :data="treeData"
        :field-names="fieldNames"
        checked-strategy="child"
        checkable
        multiple
        default-expand-all
        @select="onSelect"
      >
        <template #switcher-icon="node, { isLeaf }">
          <icon-down
            v-if="!isLeaf"
            class="text-3 !text-black"
          />
        </template>
        <template #title="nodeData">
          <template v-if="getMatchIndex(nodeData?.name) < 0">
            {{ nodeData?.name }}
            <span class="text-#165dff">
              <span
                v-if="nodeData.type"
                class="text-12px text-#86909C"
              >({{ getOptionsLabel(typeOptions, nodeData.type) }})</span>
            </span>
          </template>
          <span v-else>
            {{ nodeData?.name?.substr(0, getMatchIndex(nodeData?.name)) }}
            <span style="color: #165dff">
              {{
                nodeData?.name?.substr(
                  getMatchIndex(nodeData?.name),
                  searchKey.length,
                )
              }} </span>{{
              nodeData?.name?.substr(
                getMatchIndex(nodeData?.name) + searchKey.length,
              )
            }}
          </span>
        </template>
        <!-- <template #icon="{ node }">
          <i-icons-l1 v-if="node.level && node.level === 1" />
          <i-icons-l2 v-else-if="node.level && node.level === 2" />
        </template> -->
      </a-tree>
      <div
        v-else
        class="empty-data"
      >
        <!-- <i-icons-deploy-empty /> -->
        <span class="text-5 text-sm/22px">暂无数据</span>
      </div>
    </section>
  </section>
</template>

<style lang="less" scoped>
:deep(.arco-tree) {
  .arco-tree-node {
    .arco-checkbox {
      @apply h-22px;
    }
  }

  .arco-tree-node-title {
    @apply text-[#1D2129] h-22px !text-sm/22px select-none flex !items-center;

    .arco-tree-node-icon {
      @apply leading-22px flex flex-center justify-center;
    }
  }

  [data-level='0'] {
    @apply !w-full pb-4;

    &:not(:first-child) {
      @apply !pt-4;
    }

    .arco-tree-node-title > .arco-tree-node-icon {
      @apply !mr-0;
    }

    .arco-tree-node-switcher {
      @apply !h-22px !leading-22px;

      &:has(.arco-icon) {
        @apply !text-4;
      }
    }
  }

  .arco-tree-node-switcher {
    @apply !h-22px !leading-22px;

    &:has(.arco-icon) {
      @apply !text-4;
    }
  }

  .arco-tree-node-is-leaf {
    @apply !min-w-320px float-left !leading-22px pb-4;

    .arco-tree-node-indent > .arco-tree-node-indent-block {
      @apply mr-14px;
    }

    .arco-tree-node-title > .arco-tree-node-title-text {
      @apply truncate !max-w-350px select-none;
    }
  }
}

:deep(.arco-input-search .arco-icon-hover) {
  //@apply text-7;
}

.empty-data {
  @apply flex flex-col justify-center items-center w-full h-full min-h-500px bg-white;
  // height: calc(100vh - 312px);
}
</style>
